package com.bristua.mall.wx.biz;

import com.bristua.mall.common.utils.CacheUtil;
import com.bristua.mall.common.utils.JsonUtil;
import com.bristua.mall.wx.controller.AppWxLoginController;
import com.bristua.mall.wx.model.WXConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import springfox.documentation.spring.web.json.Json;

import java.util.Map;

/**
 * Created by Administrator on 2019/4/17.
 */
@Component
public class AppGetTokenBiz {
    private static final Logger logger = LoggerFactory.getLogger(AppGetTokenBiz.class);
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private WXConfig wxConfig;

    @Autowired
    private CacheUtil cacheUtil;

    @Autowired
    private AsyncAddWxUserBiz asyncAddWxUserBiz;

    public String appGetToken(String code,String openId){
        if(!StringUtils.isEmpty(openId)){
            Object token = cacheUtil.getToken(openId);
            if(token!=null){
                return token.toString();
            }
        }
        String appGetTokenUrl = wxConfig.getAppGetTokenUrl();
        appGetTokenUrl = String.format(appGetTokenUrl,wxConfig.getAppid(),wxConfig.getAppSecret(),code);
        ResponseEntity<String> forEntity = restTemplate.getForEntity(appGetTokenUrl, String.class);
        String body = forEntity.getBody();
        logger.info("==>token msg:"+body);
        Map map = JsonUtil.json2Map(body);
        String token = String.valueOf(map.get("access_token"));
        String openid = String.valueOf(map.get("openid"));
        String expires_in = cacheUtil.put(openid, token, Long.valueOf(Double.valueOf(String.valueOf(map.get("expires_in"))).intValue()));
        return asyncAddWxUserBiz.addWxUser(openid,expires_in);
    }
//
//    public static void main(String[] args) {
//        String a = "20.0";
//        int i = Double.valueOf(a).intValue();
//        System.out.println(i);
//    }
}
